﻿using AiQiuQuan.Sport.Model.Models;
using MapsterMapper;
using Microsoft.EntityFrameworkCore;
using System.Text;

namespace AiQiuQuan.Sport.WebApi
{
    /// <summary>
    /// 扩展
    /// </summary>
    public static class StaticExtension
    {
        /// <summary>
        /// 分页扩展
        /// </summary>
        public static async Task<PageResult<TEntity>> PageListAsync<TEntity>(this IOrderedQueryable<TEntity> queryable, PageRequest page)
        {
            return await PageListAsync(queryable, page.PageIndex, page.PageSize);
        }

        /// <summary>
        /// 分页扩展
        /// </summary>
        public static async Task<PageResult<TEntity>> PageListAsync<TEntity>(this IOrderedQueryable<TEntity> queryable, int pageIndex, int pageSize)
        {
            return new PageResult<TEntity>
            {
                Total = await queryable.CountAsync(),
                Result = await queryable.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync()
            };
        }

        /// <summary>
        ///  分页扩展
        /// </summary>
        /// <typeparam name="TEntity">实体</typeparam>
        /// <typeparam name="TResult">返回模型</typeparam>
        public static async Task<PageResult<TResult>> PageListAsync<TEntity, TResult>(this IOrderedQueryable<TEntity> queryable, int pageIndex, int pageSize, IMapper mapper)
        {
            return new PageResult<TResult>
            {
                Total = await queryable.CountAsync(),
                Result = await queryable.Skip((pageIndex - 1) * pageSize).Take(pageSize).Select(m => mapper.Map<TResult>(m)).ToListAsync()
            };
        }

        /// <summary>
        ///  分页扩展
        /// </summary>
        /// <typeparam name="TEntity">实体</typeparam>
        /// <typeparam name="TResult">返回模型</typeparam>
        public static async Task<PageResult<TResult>> PageListAsync<TEntity, TResult>(this IOrderedQueryable<TEntity> queryable, PageRequest page, IMapper mapper)
        {
            return await PageListAsync<TEntity, TResult>(queryable, page.PageIndex, page.PageSize, mapper);
        }

        /// <summary>
        /// 集合转字符串
        /// </summary>
        public static string ListToString<T>(this IEnumerable<T> source, string separator = ",")
        {
            if (source?.Count() == 0)
            {
                return string.Empty;
            }

            separator ??= ",";
            var builder = new StringBuilder();
            foreach (var item in source)
            {
                builder.Append($"{item}{separator}");
            }

            return builder.ToString().TrimEnd(separator.ToCharArray());
        }
    }
}
